package io.renren.modules.generator.controller;

/**
 * @author rose
 * @create 2021/8/7
 */


import cn.hutool.core.io.FileUtil;

import cn.hutool.core.util.CharsetUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import io.renren.common.exception.RRException;
import io.renren.common.utils.FTPUtils;
import io.renren.common.utils.FileUtils;
import io.renren.common.utils.R;
import io.renren.common.utils.TimeUtils;
import io.renren.modules.generator.dto.FireData;
import io.renren.modules.generator.dto.JsonRootBean;
import io.renren.modules.generator.entity.FireForecastDataEntity;
import io.renren.modules.generator.service.FireForecastDataService;
import io.renren.modules.generator.util.FTPUtil;
import io.renren.modules.job.service.HttpClientService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Api(tags = "FTP相关接口" , description = "FTPController | FTP模块")
public class FTPController {

    @Autowired
    private FTPUtils ftpUtils;

    @Autowired
    private FireForecastDataService fireForecastDataService;




//    @RequestMapping("/uploadToFtp")
//    public String uploadToFtp() {
//        File file = new File("D:\\skills1.txt");
//        InputStream inputStream = FileUtil.getInputStream(file);
//        try {
//            ftpUtils.uploadToFtp(inputStream, "skills3.txt", false);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return "SUCCESS";
//    }

    @ApiOperation("生成当前FTP目录")
    @GetMapping("/getPath")
    public String getPath() {
        return FTPUtil.genePath();
    }

    @ApiOperation("根据经纬度查看当前的地理位置")
    @GetMapping("/getAddress")
    public R getAddress(String lng,String lat) throws Exception {
        List<NameValuePair> list = new ArrayList<>();

        list.add(new BasicNameValuePair("type", "geocode"));
        list.add(new BasicNameValuePair("tk", "9853468a2871b2835892b78b2b6015bc"));
        list.add(new BasicNameValuePair("postStr", "{'lon':" + lng + ",'lat':" + lat + ",'ver':1}"));
        JSONObject json = (JSONObject) HttpClientService.sendGet("http://api.tianditu.gov.cn/geocoder", list);
        JsonRootBean jsonRootBean = JSON.parseObject(json.toString(), JsonRootBean.class);
        return R.ok().put("jaon",jsonRootBean);
    }



    @ApiOperation("从FTP上面拿去CSV数据并且存入数据库")
    @GetMapping("/downloadFile")
    public String downloadFile() {
        try {
            String path = FTPUtil.genePath();
            InputStream inputStream = ftpUtils.downloadFile(path);
            // 定义文件存储路径，并创建相关文件夹
            String basePath = FileUtils.getRootPath();
            System.out.println(basePath);

            //文件后缀变大写
            String suffix = ".CSV";
            String savePath = "UploadFiles/"+ "Temporary/" + TimeUtils.formatDate2String(new Date(),"yyyyMM/");
            File fileDir = new File(basePath + savePath);
            //我这个项目这里有中文所以出现了很大的问题；

            if (!fileDir.exists()) fileDir.mkdirs();
            String fileName = TimeUtils.formatDate2String(new Date(), "yyyyMMddHHmmssSSS") + suffix.toLowerCase();
            System.out.println(fileName);
            Thread.sleep(2);
            if (inputStream == null){
                throw new RRException("请再次发送请求");
            }
            String fullFilePath= basePath + savePath+fileName;
            System.out.println();
            FileUtil.writeFromStream(inputStream, fullFilePath);
            Thread.sleep(4);
            //这里开始进入解析csv
            fireForecastDataService.parseCSV(fullFilePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "SUCCESS";
    }

    @ApiOperation("通过上传csv文件解析想要的数据")
    @PostMapping("/parseByName")
    public List parseByName(MultipartFile file) throws IOException {
        InputStreamReader inputStream = new InputStreamReader(file.getInputStream(), CharsetUtil.CHARSET_GBK);
        // 设置解析策略，csv的头和POJO属性的名称对应，也可以使用@CsvBindByName注解来指定名称
        HeaderColumnNameMappingStrategy strategy = new HeaderColumnNameMappingStrategy();
        strategy.setType(FireData.class);

        CsvToBean csvToBean = new CsvToBeanBuilder(inputStream)
                .withMappingStrategy(strategy)
                .build();
        List<FireData> carCsvDTOList = csvToBean.parse();
        List<FireForecastDataEntity> collect = carCsvDTOList.stream().map(
                (item) -> {
                    FireForecastDataEntity entity = new FireForecastDataEntity();
                    BeanUtils.copyProperties(item, entity);
                    // todo 这块还没有设置发生问题的时间
                    entity.setFireTime(new Date());
                    List<NameValuePair> list = new ArrayList<>();

                    list.add(new BasicNameValuePair("type", "geocode"));
                    list.add(new BasicNameValuePair("tk", "9853468a2871b2835892b78b2b6015bc"));
                    list.add(new BasicNameValuePair("postStr", "{'lon':" + item.getLng() + ",'lat':" + item.getLat() + ",'ver':1}"));
                    try {
                        JSONObject json = (JSONObject) HttpClientService.sendGet("http://api.tianditu.gov.cn/geocoder", list);

                        JsonRootBean jsonRootBean = JSON.parseObject(json.toString(), JsonRootBean.class);
                        entity.setAddress(jsonRootBean.getResult().getAddressComponent().getAddress());
                        entity.setAddressCode(jsonRootBean.getResult().getAddressComponent().getCounty_code());
                        if (jsonRootBean.getResult().getAddressComponent().getCounty_code() != null){
                            boolean flag = jsonRootBean.getResult().getAddressComponent().getCounty_code().equals("");
                            if ( flag != true){
//                            System.out.println(jsonRootBean.getResult().getAddressComponent().getCounty_code().substring(0,5));
//                            System.out.println(jsonRootBean.getResult().getAddressComponent().getCounty_code().substring(3));
                                if (jsonRootBean.getResult().getAddressComponent().getCounty_code().substring(0,5).equals("15613")){
                                    entity.setAddressCode(jsonRootBean.getResult().getAddressComponent().getCounty_code().substring(3));
                                    System.out.println("存储");
                                    fireForecastDataService.save(entity);
                                }
                            }
                        }


                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    return entity;
                }
        ).collect(Collectors.toList());

        return collect;
    }
}

